package com.zhao.dota.security.filter;

import com.zhao.dota.bo.AuthenticateUser;
import com.zhao.dota.security.handler.LoginExpiredHandler;
import com.zhao.dota.security.store.TokenStore;
import com.zhao.dota.security.token.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

public class AuthenticationFilter extends BasicAuthenticationFilter {

    @Resource
    private TokenStore tokenStore;
    @Resource
    private LoginExpiredHandler loginExpiredHandler;

    @Autowired
    public AuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        if (token == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                chain.doFilter(request, response);
                return;
            }
            Optional<Cookie> first = Arrays.stream(cookies).filter(Objects::nonNull)
                    .filter(c -> "Authorization".equals(c.getName())).findFirst();
            if (first.isPresent()) {
                Cookie cookie = first.get();
                token = cookie.getValue();
            } else {
                chain.doFilter(request, response);
                return;
            }
        }
        AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null) {
            chain.doFilter(request, response);
            return;
        }
        AuthenticateUser authenticateUser = tokenStore.readAuthentication(accessToken);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            if (authenticateUser == null) {
                chain.doFilter(request, response);
                return;
            }
            if (authenticateUser.getId() == null) {
                chain.doFilter(request, response);
                return;
            }
            authentication = new UsernamePasswordAuthenticationToken(authenticateUser, null, authenticateUser.getAuthorities());
        } else {
            AuthenticateUser principal = (AuthenticateUser) authentication.getPrincipal();
            if (authenticateUser == null || !Objects.equals(principal.getId(), authenticateUser.getId())) {
                chain.doFilter(request, response);
                return;
            }
        }
        if (accessToken.isExpired()) {
            expired(request, response, accessToken);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private void expired(HttpServletRequest request, HttpServletResponse response, AccessToken accessToken) throws IOException {
        loginExpiredHandler.onAccessTokenExpired(request, response);
    }

}
